<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/3/8
 * Time: 下午4:07
 */

namespace backend\controllers;

use common\jobs\UpdateCouponJob;
use common\models\TempUserCoupon;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii;

class TempCouponController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $dataProvider = new yii\data\ActiveDataProvider(['query' => TempUserCoupon::find()]);
        return $this->render('index', ['dataProvider' => $dataProvider]);
    }

    public function actionExecute($id)
    {
        $model = $this->findModel($id);
        Yii::$app->queue->push(new UpdateCouponJob([
            'couponId' => $model->coupon_id,
            'userId' => $model->user_id
        ]));
        Yii::$app->session->addFlash('success', '加入队列成功');
        return $this->redirect(['index']);
    }

    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        if ($model->delete()) {
            Yii::$app->session->addFlash('success', '删除成功');
            return $this->redirect(['index']);
        }
    }

    public function findModel($id)
    {
        $model = TempUserCoupon::findOne($id);
        if ($model !== null) {
            return $model;
        }
        throw new NotFoundHttpException("资源不存在");
    }
}
